#! python3

import os
import sys
import chardet

g_curFolder = sys.path[0]+"\\"

# "E:\\Users\\yinxunqian\\Documents\\xcl_files\\Sql"
# "E:\\Users\\yinxunqian\\sql_Script"
# "E:\\Users\\yinxunqian\\sql_Script\\＃NewYGC"

g_targetPath = "E:\\Users\\yinxunqian\\sql_Script\\＃NewYGC"

g_searchstr = "AbpUserRoles"

def SearchPath(path, txt):
    itemlist = os.listdir(path)
    for f in itemlist:
        fullpath = path + "/" + f
        if(os.path.isfile(fullpath)):
            # check content 
            if(CheckContent(g_searchstr, fullpath)):
                Record(fullpath, txt)
            
        if(os.path.isdir(fullpath)):
            SearchPath(fullpath, txt)

def Record(msg, path):
    with open(path,'a', encoding='utf8') as fr:
        fr.write(msg)
        fr.write('\n')



def CheckContent(sear, path):
    encodingstr = GetEncode(path)

    with open(path, "r+", encoding=encodingstr,errors='ignore') as f :
        for l in f.readlines():
            if(sear in l):
                print('11')
                return True
    
    return False

def GetEncode(path):
    encodestr = "utf-8"
    ftest = open(file=path,mode='rb')
    dr = chardet.detect(ftest.read())
    ftest.close()
    #print(path + " *** " + str(encodestr))
    if(dr['confidence'] == 1.0):
        encodestr = dr['encoding']

    return encodestr


def main(curpath, tarpath):
    print("start...")

    #cur = os.getcwd() + "/LPractice"
    _txt = curpath + "//r1.txt"
    if(os.path.isfile(_txt)):
        os.remove(_txt)
    
    SearchPath(tarpath, _txt)
    print("final done...")

main(g_curFolder,g_targetPath)

# print("done...")